#include <RTC.h>
#include <sys.h>

const unsigned char days[24] = {31,28,31,30,31,30,31,31,30,31,30,31,31,29,31,30,31,30,31,31,30,31,30,31};
unsigned char Is_leap = 0;
void RTC_IRQHandler(void)
{
	RTC->CRL &= ~SECF;
	LED1 = !LED1;
	/*RCC->APB1ENR |= PWREN;
	PWR->CR |= DBP;

	++BKP->DR4;	//加一秒
	if((BKP->DR4 & 0x00FF) > 59)
	{
		BKP->DR4 -= 60;
		BKP->DR4 += 0x0100;	//加一分钟
	}
	if((BKP->DR4 & 0xFF00) > 0x3B00)
	{
		BKP->DR4 -= 0x3C00;
		++BKP->DR3;	//加一小时
	}
	if((BKP->DR3 & 0x00FF) > 23)
	{
		BKP->DR3 -= 24;
		BKP->DR3 += 0x0100;	//加一天
	}
	if((BKP->DR3 & 0xFF00) > days[Is_leap*12 + (BKP->DR2 & 0x000F)])
	{

	}
	RCC->APB1ENR &= ~PWREN;*/
}
//读后备数据寄存器，检查是否发生备份域复位
unsigned char RTC_Check(void)
{
	RCC->APB1ENR |= PWREN|BKPEN;
	PWR->CR |= DBP;
	if(BKP->DR1 == 0x5555)
	{
		//更新时间
		while((RTC->CRL & RSF) == 0);

		return 0;	//后备域没有被复位
	}
	BKP->DR1 = 0x5555;
	RTC_Init(32767);
	RCC->APB1ENR &= ~PWREN;
	return 1;	//后备域被复位，需重设时间
}
//初始化RTC预分频数、中断设置
unsigned char RTC_Init(unsigned int prl)
{	//LSE频率是32.768kHz
	unsigned short times = 0;
	RCC->BDCR |= LSEON;
	while((RCC->BDCR & LSERDY)==0 && times != 0xFFFF)
		++times;
	if(times == 0xFFFF)
		return 1;
	RCC->BDCR |= RTCEN|LSECK;
	while((RTC->CRL & RTOFF) == 0);
	RTC->CRL |= CNF;
	RTC->PRLL = (unsigned short)prl;
	RTC->PRLH = (unsigned short)prl>>16;
	RTC->CRL &= ~CNF;
	RTC->CRH |= SECIE;
	MY_NVIC_Init(2,2,RTC_IRQn,2);
	while((RTC->CRL & RTOFF) == 0);
	return 0;
}
//重设置系统时间
void Time_Reset(struct Time *start_time)
{
	RCC->APB1ENR |= PWREN|BKPEN;
	PWR->CR |= DBP;

	BKP->DR2 = start_time->year;
	BKP->DR2 <<= 4;	//低4位用来保存month
	BKP->DR2 |= start_time->month;
	BKP->DR3 = start_time->date;
	BKP->DR3 <<= 8;
	BKP->DR3 |= start_time->hour%24;
	BKP->DR4 = start_time->minute%60;
	BKP->DR4 <<= 8;
	BKP->DR4 |= start_time->second%60;
	
	RCC->APB1ENR &= ~PWREN;
}

void Get_time(struct Time *current_time)
{
	RCC->APB1ENR |= PWREN;
	PWR->CR |= DBP;
	current_time->year   = BKP->DR2 >> 4;
	current_time->month  = (unsigned char)BKP->DR2 & 0x000F;
	current_time->date   = (unsigned char)BKP->DR3 >> 8;
	current_time->hour   = (unsigned char)BKP->DR3 & 0x00FF;
	current_time->minute = (unsigned char)BKP->DR4 >>8;
	current_time->second = (unsigned char)BKP->DR4 & 0x00FF;
	RCC->APB1ENR &= ~PWREN;
}
